#include "include/Server.h"
#include "include/Singleton.h"
#include "include/Configuration.h"

Server::Server()
	: _io_service_pool(Singleton<Configuration>::instance().thread_count),
	_acceptor(_io_service_pool.GetIoService(), tcp::endpoint(tcp::v4(), Singleton<Configuration>::instance().port)),
	_control_acceptor(_io_service_pool.GetControlService(), tcp::endpoint(tcp::v4(), Singleton<Configuration>::instance().control_port))
{
	Session *new_session = new Session(_io_service_pool.GetIoService());
	
	_acceptor.async_accept(new_session->Socket(),
		boost::bind(&Server::HandleAccept, this, new_session, boost::asio::placeholders::error));
		
	Session *control_session = new Session(_io_service_pool.GetControlService());
	_control_acceptor.async_accept(control_session->Socket(),
		boost::bind(&Server::HandleControlAccept, this, control_session, boost::asio::placeholders::error));
}

Server::~Server()
{
}

void Server::Run()
{
	_io_service_pool.Start();
	_io_service_pool.Join();
}

void Server::HandleAccept(Session *new_session, const boost::system::error_code &error)
{
	if(error)
	{
		delete new_session;
		return;
	}

	// debug
	cout << "get one client" << endl;

	new_session->Start();

	new_session = new Session(_io_service_pool.GetIoService());
	_acceptor.async_accept(new_session->Socket(),
		boost::bind(&Server::HandleAccept, this, new_session, boost::asio::placeholders::error));
}

void Server::HandleControlAccept(Session *control_session, const boost::system::error_code &error)
{
	if(error)
	{
		delete control_session;
		return;
	}

	control_session->StartControl();
	control_session = new Session(_io_service_pool.GetControlService());

	_control_acceptor.async_accept(control_session->Socket(),
		boost::bind(&Server::HandleControlAccept, this, control_session, boost::asio::placeholders::error));
}
